/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.internal.core.handler;

import com.helger.jcodemodel.AbstractJClass;
import com.helger.jcodemodel.JDefinedClass;
import com.helger.jcodemodel.JFieldRef;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.holder.EComponentWithViewSupportHolder;
import org.ohosannotations.holder.FoundViewHolder;
import org.ohosannotations.rclass.IRClass;

import java.util.List;

import javax.lang.model.element.Element;

import static com.helger.jcodemodel.JExpr._new;

/**
 * 抽象视图侦听器处理程序
 *
 * @author dev
 * @since 2021-06-03
 */
public abstract class AbstractViewListenerHandler extends AbstractListenerHandler<EComponentWithViewSupportHolder> {
    /**
     * 抽象视图侦听器处理程序
     *
     * @param targetClass 目标类
     * @param environment 环境
     */
    public AbstractViewListenerHandler(Class<?> targetClass, OhosAnnotationsEnvironment environment) {
        super(targetClass, environment);
    }

    /**
     * 抽象视图侦听器处理程序
     *
     * @param target 目标
     * @param environment 环境
     */
    public AbstractViewListenerHandler(String target, OhosAnnotationsEnvironment environment) {
        super(target, environment);
    }

    @Override
    public void validate(Element element, ElementValidation valid) {
        super.validate(element, valid);
        validatorHelper.enclosingElementHasEnhancedViewSupportAnnotation(element, valid);
    }

    @Override
    protected final void assignListeners(EComponentWithViewSupportHolder holder,
        List<JFieldRef> idsRefs, JDefinedClass listenerAnonymousClass) {
        for (JFieldRef idRef : idsRefs) {
            AbstractJClass listenerTargetClass = getListenerTargetClass(holder);
            FoundViewHolder foundViewHolder = holder.getFoundViewHolder(idRef, listenerTargetClass);
            foundViewHolder.getIfNotNullBlock().invoke(foundViewHolder
                .getOrCastRef(listenerTargetClass), getSetterName()).arg(_new(listenerAnonymousClass));
        }
    }

    @Override
    protected AbstractJClass getListenerTargetClass(EComponentWithViewSupportHolder holder) {
        return getClasses().COMPONENT;
    }

    @Override
    protected final IRClass.Res getResourceType() {
        return IRClass.Res.ID;
    }
}
